package top.szhome.framework.starter.template.engine;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * Freemarker模板引擎
 *
 * @author 唐加利
 * @date 2023/7/14
 **/
@Slf4j
public class FreemarkerEngine implements TemplateEngine {

    private Configuration configuration;

    /**
     * 构造模板引擎
     */
    public FreemarkerEngine(){
        configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setDefaultEncoding("UTF-8");
        configuration.setTemplateLoader(new StringTemplateLoader());
        configuration.setClassForTemplateLoading(FreemarkerEngine.class, "/");
        configuration.setWhitespaceStripping(true);
        configuration.setBooleanFormat("true, false");
    }

    @Override
    public String process(String name, String template, Map<String, Object> context) {
        try {
            Template temp = new Template(name, template, configuration);
            StringWriter writer = new StringWriter();
            temp.process(context, writer);
            return writer.toString();
        } catch (IOException | TemplateException e) {
            log.error("模板解析异常，name={}, template={}", name, template, e);
            return null;
        }
    }

}
